import os
from datetime import datetime, timezone
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import logging

# 配置日志
logger = logging.getLogger(__name__)

# 从环境变量获取数据库连接信息，这里使用默认值作为示例
DATABASE_URL = os.getenv(
    "DATABASE_URL",
    "mysql+pymysql://root:password@localhost:3306/meeting_assistant"
)

# 创建数据库引擎
engine = create_engine(
    DATABASE_URL,
    pool_size=5,
    max_overflow=10,
    pool_timeout=30,
    pool_recycle=1800
)

# 创建会话本地类
SessionLocal = sessionmaker(
    autocommit=False,
    autoflush=False,
    bind=engine
)

# 创建基础模型类
Base = declarative_base()

# 获取数据库会话依赖项
def get_db():
    """获取数据库会话的依赖项"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# 初始化数据库
def init_database():
    """初始化数据库，创建所有表和测试账号"""
    try:
        logger.info("开始初始化数据库...")
        # 创建所有表
        Base.metadata.create_all(bind=engine)
        
        # 导入User相关模型和服务
        from apps.users.models import User
        from apps.users.services import UserService
        import bcrypt
        
        # 创建测试账号
        db = next(get_db())
        try:
            # 检查测试账号是否已存在
            existing_user = UserService.get_user_by_username(db, "test")
            if not existing_user:
                # 创建测试账号，密码使用bcrypt加密
                hashed_password = bcrypt.hashpw("test123!".encode('utf-8'), bcrypt.gensalt())
                test_user = User(
                    username="test",
                    email="test@example.com",
                    password_hash=hashed_password.decode('utf-8'),
                    is_active=True,
                    created_at=datetime.now(timezone.utc),
                    updated_at=datetime.now(timezone.utc)
                )
                db.add(test_user)
                db.commit()
                logger.info("测试账号创建成功: username=test, password=test123!")
            else:
                logger.info("测试账号已存在")
        finally:
            db.close()
        
        logger.info("数据库初始化成功")
    except Exception as e:
        logger.error(f"数据库初始化失败: {str(e)}")
        raise